import os

import facade
from xjlibrary.our_file_dir import BaseDir, ImageFile

curPath = BaseDir.get_file_dir_absolute(__file__)
configfile = BaseDir.get_new_path(curPath, "db.ini")
TopPath = BaseDir.get_upper_dir(curPath, -2)
coverPath = BaseDir.get_new_path(TopPath, "download", "astmjournal", "download", "cover")
BaseDir.create_dir(coverPath)


class DownCover(object):
    def __init__(self):
        self.logger = facade.get_streamlogger()
        self.mysqlutile = facade.MysqlUtiles(configfile, "db", logger=self.logger)

    def select(self):
        sql = "select imageurl,journal from journal"
        rows = self.mysqlutile.SelectFromDB(sql)
        for row in rows:
            baseurl = "https://www.astm.org/DIGITAL_LIBRARY/JOURNALS/"
            url = baseurl + row[0]
            BoolResult, errString, r = facade.BaseRequest(url,
                                                          endstring="",
                                                          verify=False,
                                                          allow_redirects=True,
                                                          timeout=60)
            if BoolResult:
                if BoolResult:
                    name = row[1].lower() + ".jpg"
                    ImageFile.img_to_format_jpg(r.content, BaseDir.get_new_path(coverPath, name))

    def map_cover(self):
        nCount = 0
        provider = 'astmjournal'
        filePath = provider + '_cover.txt'
        print('path:' + coverPath)

        with open(filePath, mode='w', encoding='utf-8') as f:
            for path, dirNames, fileNames in os.walk(coverPath):
                for fileName in fileNames:
                    # 分离文件名与扩展名 返回文件名和扩展名
                    journal = os.path.splitext(fileName)[0].upper()
                    line = provider + '@' + journal + '★/smartlib/' + provider + '/' + fileName + '\n'
                    f.write(line)
                    nCount += 1
        print('nCount:' + str(nCount))


def main():
    down = DownCover()
    down.select()
    down.map_cover()


if __name__ == "__main__":
    main()
